package global

import (
	"os"
	"os/signal"
	"sync/atomic"
	"time"

	"github.com/astaxie/beego/logs"
)

const (
	//StatusStop 停止
	StatusStop = 0
	//StatusStart 启动
	StatusStart = 1
	//StatusRunning 运行中
	StatusRunning = 2
	//StatusPause 暂停
	StatusPause = 3
)

//status 运行状态
var status int32 = StatusStop
var exitChan chan byte = make(chan byte, 0)

//WaitExit 等待退出
func WaitExit() <-chan byte {
	return exitChan
}

func signalListen() {
	sign := make(chan os.Signal)
	signal.Notify(sign, os.Interrupt)
	<-sign
	Stop()
}

//Start 启动
func Start() bool {
	atomic.StoreInt32(&status, StatusRunning)
	go signalListen()
	return true
}

//Stop 停止
func Stop() bool {
	atomic.StoreInt32(&status, StatusStop)
	close(exitChan)
	go Timeout()
	return true
}

//Timeout 超时
func Timeout() {
	select {
	case <-time.After(time.Second * 10):
		logs.Warn("Exit time out")
		os.Exit(2)
	}
}

//IsRunning 是否在运行
func IsRunning() bool {
	return (status != StatusStop)
}

//Sleep 睡眠
func Sleep(ms int) {
	for ms > 0 && IsRunning() {
		if ms > 1000 {
			time.Sleep(time.Second)
			ms -= 1000
		} else {
			time.Sleep(time.Millisecond * time.Duration(ms))
			break
		}
	}
}
